package com.gitee.zjbqdzq.util;

import lombok.Getter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Function;

public class HibernateUtil {
    @Getter
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // 创建会话工厂
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static void shutdown() {
        // 关闭缓存和连接池
        getSessionFactory().close();
    }

    public static void execute(Consumer<Session> consumer) {
        try (Session session = sessionFactory.openSession()) {
            Transaction transaction = session.beginTransaction();
            consumer.accept(session);
            transaction.commit();
        }
    }

    public static <T> T getOne(Function<Session, T> runnable) {
        try (Session session = sessionFactory.openSession()) {
            return runnable.apply(session);
        }
    }

    public static <T> Collection<T> get(Function<Session, Collection<T>> runnable) {
        try (Session session = sessionFactory.openSession()) {
            return runnable.apply(session);
        }
    }
}

